/**
 * @name        theStore.ts
 * @author      shenyc
 * @date        2020-05-06 - ?
 * @copyright   Copy right (c) shenyc (shenyczz@163.com).
 *              All rights reserved.
 *
 ******************************************************************************/
// {{@@@}}
"use strict"
// ----------------------------------------------------------------------------
import utils from "@/utils"
import { type PiniaPluginContext } from "pinia"
import piniaPluginPersistedstate from "pinia-plugin-persistedstate"
import { createPersistedState, type PersistenceOptions } from "pinia-plugin-persistedstate"
// ----------------------------------------------------------------------------
/**
 * 默认存储
 *@see {@link localStorage}, {@link sessionStorage}
 */
const _defaultStorage: Storage = localStorage
const defaultStorage = () => _defaultStorage

/**
 * 默认持久化状态
 */
const persistedStateDefault = piniaPluginPersistedstate

/**
 * 自定义持久存储插件 - how tu use it?
 */
const persistedStateCustom = createPersistedState({
    key: (id: string) => utils.getPreFixString(id),
    storage: _defaultStorage,
    auto: false,
    debug: true,
})

/**
 * @description pinia 持久化参数配置
 * @param {string} id 存储到持久化的 name
 * @return {PersistenceOptions} persistenceOptions 持久选项
 * */
const persistedStateConfig = (id: string, pick?: string[], omit?: string[]): PersistenceOptions => {
    // 持久选项参数
    const persistenceOptions: PersistenceOptions = {
        key: id, // Storage key to use. default $store.id
        storage: _defaultStorage, // sessionStorage
        // serializer: {
        //     serialize: (state) => JSON.stringify(state),
        //     deserialize: (data: string) => JSON.parse(data),
        // },
        pick: pick, // 在持久化之前从状态中选择的点表示法路径。
        omit: omit,
        beforeHydrate: (ctx: PiniaPluginContext) => {
            // console.log(`about to hydrate '${ctx.store.$id}'`)
        },
        afterHydrate: (ctx: PiniaPluginContext) => {
            // console.log(`just hydrated '${ctx.store.$persist}'`)
            // persistedStateDefault.
        },
        debug: true, // Log errors in console.
    }
    return persistenceOptions
}

/**
 * 存储 ID
 */
const StoreID = {
    LOCALE_STORE: utils.getPreFixString("LocaleStore"),
    // DARK_STORE: utils.getPreFixString("DarkStore"),
}

export { StoreID, defaultStorage, persistedStateDefault, persistedStateConfig, persistedStateCustom }
// ----------------------------------------------------------------------------
// {{@@@}}
